<template>
    <div class="app-container">
      <!-- 查询区域 -->
      <el-card class="search-card">
        <el-form :model="queryParams" :inline="true">
          <el-form-item label="用户">
            <el-select 
              v-model="queryParams.userId" 
              placeholder="请选择用户" 
              clearable
              filterable
              style="width: 250px"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 数据表格区域 -->
      <el-card class="mt-2">
        <!-- 操作按钮和右侧工具栏 -->
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <div>
              <el-button type="primary" @click="handleAdd" icon="Plus">新增</el-button>
            </div>
          </el-col>
          <el-col :span="12" class="flex-end">
            <right-toolbar 
              :search="false" 
              v-model:showSearch="showSearch" 
              @queryTable="fetchUserFeatureList"
              :columns="columns"
            ></right-toolbar>
          </el-col>
        </el-row> -->
  
        <!-- 数据表格 -->
        <el-table 
          :data="userFeatureList" 
          border 
          v-loading="loading"
          class="mt-2"
        >
          <el-table-column 
            prop="userId" 
            label="用户ID" 
            width="100" 
            align="center" 
            v-if="columns[0].visible"
          />
          <el-table-column 
            prop="username" 
            label="用户账号" 
            align="center" 
            v-if="columns[1].visible"
          />
          <el-table-column 
            label="导航栏功能" 
            align="center" 
            v-if="columns[2].visible"
          >
            <template #default="{ row }">
              <el-tag 
                v-for="feature in row.navFeatureIds" 
                :key="feature.id"
                type="info"
                class="mr-1 mb-1"
              >
                {{ feature.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column 
            label="功能权限" 
            align="center" 
            v-if="columns[3].visible"
          >
            <template #default="{ row }">
              <el-tag 
                v-for="feature in row.featureIds" 
                :key="feature.id"
                class="mr-1 mb-1"
              >
                {{ feature.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column 
            label="操作" 
            width="150" 
            align="center" 
            fixed="right"
            v-if="columns[4].visible"
          >
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页区域 -->
        <el-pagination
          class="mt-2"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:page-size="queryParams.pageSize"
          v-model:current-page="queryParams.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
  
      <!-- 新增/编辑对话框 -->
      <el-dialog 
        v-model="dialog.visible" 
        :title="dialog.title" 
        width="800px"
        :close-on-click-modal="false"
      >
        <el-form 
          ref="formRef" 
          :model="form" 
          :rules="rules" 
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="用户" prop="userId">
                <el-select 
                  v-model="form.userId" 
                  placeholder="请选择用户" 
                  style="width: 100%"
                  filterable
                  :disabled="dialog.isEdit"
                >
                  <el-option
                    v-for="item in userOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 导航栏功能多选框 -->
          <el-form-item label="导航栏功能">
            <el-checkbox-group v-model="form.navFeatureIds">
              <el-row :gutter="20">
                <el-col :span="8" v-for="feature in navFeatureOptions" :key="feature.id">
                  <el-checkbox :label="feature.id">{{ feature.name }}</el-checkbox>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </el-form-item>
          
          <!-- 功能权限多选框 -->
          <el-form-item label="功能权限">
            <el-checkbox-group v-model="form.featureIds">
              <el-row :gutter="20">
                <el-col :span="8" v-for="feature in featureOptions" :key="feature.id">
                  <el-checkbox :label="feature.id">{{ feature.name }}</el-checkbox>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import RightToolbar from '@/components/RightToolbar'
  import {
    getUserList,
    getFeatureList,
    listUserFeatures,
    getUserFeatureDetail,
    addUserFeature,
    updateUserFeature
  } from '@/api/system/app_setting/user_auth'
  
  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    userId: undefined
  })
  
  // 表单数据
  const form = reactive({
    userId: undefined,
    featureIds: [],
    navFeatureIds: []
  })
  
  // 对话框控制
  const dialog = reactive({
    visible: false,
    title: '新增用户功能权限',
    isEdit: false
  })
  
  // 表格数据
  const userFeatureList = ref([])
  const total = ref(0)
  const loading = ref(false)
  const formRef = ref()
  const showSearch = ref(true)
  
  // 下拉选项数据
  const userOptions = ref([])
  const navFeatureOptions = ref([])
  const featureOptions = ref([])
  
  // 列显隐配置
  const columns = ref([
    { key: 0, label: '用户ID', visible: true },
    { key: 1, label: '用户账号', visible: true },
    { key: 2, label: '导航栏功能', visible: true },
    { key: 3, label: '功能权限', visible: true },
    { key: 4, label: '操作', visible: true }
  ])
  
  // 表单验证规则
  const rules = reactive({
    userId: [
      { required: true, message: '请选择用户', trigger: 'change' }
    ]
  })
  
  // 获取用户下拉列表
  const fetchUserList = async () => {
    try {
      const res = await getUserList()
      userOptions.value = res.data || []
    } catch (error) {
      console.error('获取用户列表失败:', error)
      ElMessage.error('获取用户列表失败')
    }
  }
  
  // 获取功能列表
  const fetchFeatureList = async () => {
    try {
      // 获取导航栏功能
      const navRes = await getFeatureList(1)
      navFeatureOptions.value = navRes.data || []
      
      // 获取普通功能
      const featureRes = await getFeatureList(2)
      featureOptions.value = featureRes.data || []
    } catch (error) {
      console.error('获取功能列表失败:', error)
      ElMessage.error('获取功能列表失败')
    }
  }
  
  // 获取用户功能权限列表
  const fetchUserFeatureList = async () => {
    try {
      loading.value = true
      const res = await listUserFeatures(queryParams)
      userFeatureList.value = res.rows || []
      total.value = res.total || 0
    } catch (error) {
      console.error('获取用户功能权限列表失败:', error)
      ElMessage.error('获取用户功能权限列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 查询按钮
  const handleQuery = () => {
    queryParams.pageNum = 1
    fetchUserFeatureList()
  }
  
  // 重置查询
  const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.userId = undefined
    fetchUserFeatureList()
  }
  
  // 分页大小变化
  const handleSizeChange = (size) => {
    queryParams.pageSize = size
    fetchUserFeatureList()
  }
  
  // 当前页码变化
  const handleCurrentChange = (page) => {
    queryParams.pageNum = page
    fetchUserFeatureList()
  }
  
  // 新增按钮
  const handleAdd = () => {
    dialog.visible = true
    dialog.title = '新增用户功能权限'
    dialog.isEdit = false
    resetForm()
  }
  
  // 编辑按钮
  const handleEdit = async (row) => {
    try {
      const res = await getUserFeatureDetail(row.userId)
      Object.assign(form, {
        userId: res.data.userId,
        featureIds: res.data.featureIds.map(item => item.id),
        navFeatureIds: res.data.navFeatureIds.map(item => item.id)
      })
      dialog.visible = true
      dialog.title = '编辑用户功能权限'
      dialog.isEdit = true
    } catch (error) {
      console.error('获取用户功能权限详情失败:', error)
      ElMessage.error('获取用户功能权限详情失败')
    }
  }
  
  // 重置表单
  const resetForm = () => {
    form.userId = undefined
    form.featureIds = []
    form.navFeatureIds = []
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }
  
  // 提交表单
  const submitForm = async () => {
    try {
      await formRef.value.validate()
      
      // 合并导航栏和功能权限
      const allFeatureIds = [...form.navFeatureIds, ...form.featureIds]
      
      if (dialog.isEdit) {
        await updateUserFeature({
          userId: form.userId,
          featureIds: allFeatureIds
        })
        ElMessage.success('更新成功')
      } else {
        await addUserFeature({
          userId: form.userId,
          featureIds: allFeatureIds
        })
        ElMessage.success('新增成功')
      }
      
      dialog.visible = false
      fetchUserFeatureList()
    } catch (error) {
      console.error('保存失败:', error)
      if (error !== 'validate') {
        ElMessage.error('操作失败')
      }
    }
  }
  
  // 初始化加载数据
  onMounted(() => {
    fetchUserList()
    fetchFeatureList()
    fetchUserFeatureList()
  })
  </script>
  
  <style scoped>
  .app-container {
    padding: 20px;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .mt-2 {
    margin-top: 20px;
  }
  
  .flex-end {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  
  /* 表格列宽自适应 */
  :deep(.el-table) {
    width: 100%;
  }
  
  :deep(.el-table__cell) {
    padding: 12px 0;
  }
  
  .mr-1 {
    margin-right: 5px;
  }
  
  .mb-1 {
    margin-bottom: 5px;
  }
  
  /* 多选框组样式 */
  :deep(.el-checkbox-group) {
    width: 100%;
  }
  
  :deep(.el-checkbox) {
    margin-right: 15px;
    margin-bottom: 10px;
  }
  </style>